<template>
  <!-- 对比分析页面 -->
  <div style="height: 100%" v-loading.fullscreen.lock="fullscreenLoading" element-loading-background="rgba(0, 0, 0, 0.8)">
    <container-item title="主动预警" hasNav>
      <div class="statistic">
        <div class="top">
          <el-form class="form-search" :model="form" inline>
            <el-form-item label="开始时间">
              <el-date-picker style="width: 300px" v-model="form.startTime" placeholder="请选择开始时间" type="datetime"
                :unlink-panels="true" clearable>
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker style="width: 300px" v-model="form.endTime" placeholder="请选择结束时间" type="datetime"
                :unlink-panels="true" clearable>
              </el-date-picker>
            </el-form-item>

            <el-form-item label="">
              <label class="btn-nav-bg stripe-btn" @click="handleSearch">查 询</label>
              <label class="btn-nav-bg stripe-btn" @click="reset">重 置</label>
            </el-form-item>
          </el-form>
          <div class="caidan_yangshi">
            <menu-element />
            <label class="btn-nav-bg stripe-btn" @click="exportData">预警报告</label>
          </div>

        </div>

        <div class="echarts-wrapper">
          <div class="echarts-wrapper-item">
            <sec-container title="换流站异常来源">
              <pie :data="stationSources"></pie>
              <!--            <div class="item">-->
              <!--            </div>-->
              <!--            <div class="item">-->
              <!--              <div class="sec-title">-->
              <!--                <img src="@/assets/images/sec-icon.png" alt="" />-->
              <!--                异常级别分析-->
              <!--              </div>-->
              <!--              <h-bar :data="stationCounts" :yName="yName"></h-bar>-->
              <!--            </div>-->
            </sec-container>
            <sec-container title="异常级别分析">
              <h-bar :data="stationCounts" :yName="yName"></h-bar>
            </sec-container>
          </div>
          <div class="echarts-wrapper-item">
            <sec-container title="告警类型统计分析">
              <bar-chart isClick @clickFn="clickFn" :xAxis="deviceCounts.xAxis" :datas="deviceCounts.data"></bar-chart>
            </sec-container>
            <sec-container title="子模块点位告警统计分析">
              <!--            <div class="item">-->
              <bar-chart isClick  :xAxis="modelPointCounts.xAxis"
                :datas="modelPointCounts.data" :rotate="45"></bar-chart>
            </sec-container>
          </div>
        </div>
      </div>
    </container-item>
    <pub-dialog :title="dialog.dialogTitle" :top="'10vh'" :dialogVisible="dialog.visible"
      dialogVisableRef="dialogVisible" @switchVisable="switchVisable" @dialogCancel="dialogCancel" class="dialog"
      btnType="2">
      <el-form ref="form" :model="dialog.form" inline label-width="130px" class="form-search">
        <el-form-item label="起止日期">
          <el-date-picker style="width: 330px" v-model="dialog.form.date" start-placeholder="开始日期"
            end-placeholder="结束日期" type="daterange" :unlink-panels="true" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
            clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="换流站">
          <el-select style="width: 360px" v-model="dialog.form.site" clearable placeholder="请选择">
            <el-option v-for="(item, idx) in siteListNew" :label="item.site" :value="item.siteId" :key="idx">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <label class="btn-nav-bg stripe-btn" @click="handleSearchDialog">查 询</label>
          <!-- <label class="btn-nav-bg stripe-btn" @click="exportExcel">导 出</label> -->
        </el-form-item>
      </el-form>
      <div class="chart-box">
        <page-table :tableData="tableData" :tableLabel="colSData" :showIndex="true" :pager="pager"
          :table-height="tableHeight" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"
          @handleButton="handleButton(arguments)"></page-table>
      </div>
    </pub-dialog>
  </div>
</template>

<script>
import SecContainer from "@/components/SecContainer";
import HBar from "@/components/HBar.vue";
import Pie from "@/components/PieChart.vue";
import BarChart from "@/components/BarChart.vue";

import ContainerItem from "@/components/ContainerItem.vue";
import MenuElement from "@/components/MenuElement/index.vue";
import {
  getSysFileQueryFileById,
  getXJHistoryDistribute,
  getXJReportFilePageList,
  // getXjSiteList,
} from "@/api/earlyWarning";
import pubDialog from "@/components/pubDialog.vue";
import PageTable from "@/components/PageTable.vue";
import Axios from "axios";
import { siteSurvey } from "@/api/earlyWarning";
import { siteList } from '@/assets/data/index';
import { handleExportFile } from '@/assets/js/fileFun';

export default {
  name: "OneType",
  components: {
    PageTable,
    pubDialog,
    BarChart,
    HBar,
    ContainerItem,
    Pie,
    // HBar,
    SecContainer,
    MenuElement,
  },

  data() {
    return {
      fullscreenLoading: false,
      huanliuShow: false, // 环流弹窗是否显示
      form: {
        startTime: this.$moment().subtract(29, "days").startOf("day").valueOf(),
        endTime: this.$moment().endOf("day").valueOf(),
      },

      // 子模块告警设备统计
      modelPointCounts: {
        data: [
          {
            name: "",
            // color: ["#83d3f6", "#1ea9ed"],
            data: [],
          },
          {
            name: "",
            // color: ["rgba(84, 61, 7, 1)", "rgba(254, 188, 34, 1)"],
            data: [],
          },
          {
            name: "",
            // color: ["#89f480", "#108707"],
            data: [],
          },
        ],
        xAxis: [],
      },
      deviceCounts: {
        data: [
          {
            name: "异常",
            color: ["rgba(84, 61, 7, 1)", "rgba(254, 188, 34, 1)"],
            data: [],
          },
          {
            name: "严重",
            color: ["#89f480", "#108707"],
            data: [],
          },
        ],
        xAxis: [],
      },

      // 换流站故障来源
      stationSources: [],
      yName: [],
      stationCounts: [
        {
          name: "异常",
          color: ["#83d3f6", "#1ea9ed"],
          data: [],
        },
        {
          name: "严重",
          color: ["rgba(84, 61, 7, 1)", "rgba(254, 188, 34, 1)"],
          data: [],
        },
      ],

      dialog: {
        dialogTitle: "",
        visible: false,
        form: {
          date: [],
          site: '',
        },
      },
      siteListNew: [],
      tableData: [],
      colSData: [
        { label: "报告名称", param: "fileName" },
        {
          param: "operate",
          label: "操作",
          width: 150,
          operate: [{ label: "下载", click: "download", type: "text" }],
        },
      ],
      pager: {
        pageSize: 10, // 每页数据量
        currentPage: 1, // 分页  当前页
        total: 0, //列表总数
      },
      tableHeight: 490,
      huanliuList: [], //换流站List
    };
  },
  mounted() {
    this.handleSearch();
    this.getSiteSurvey();
    this.siteListNew = siteList;
  },

  methods: {
    getSiteSurvey() {
      siteSurvey().then((res) => {
        if (res.code == 20000) {
          let arr = res.data;
          this.huanliuList = [...arr];
        }
      });
    },
    init() {
      let params = {
        startTime: this.$moment(this.form.startTime).format('YYYY-MM-DD HH:mm:ss'),
        endTime: this.$moment(this.form.endTime).format('YYYY-MM-DD HH:mm:ss'),
      };
      this.fullscreenLoading = true;
      getXJHistoryDistribute(params).then((res) => {
        if (res.code == 200) {
          // 换流站故障来源
          if (res.data.locationOverviews.length > 0) {
            let total = res.data.locationOverviews
              .map((item) => item.count)
              .reduce((acc, cur) => acc + cur);
            this.stationSources = res.data.locationOverviews.map((item) => {
              return {
                name: item.locationName,
                value: item.count,
                percent: ((item.count / total) * 100).toFixed(2) + "%",
              };
            });
          } else {
            this.stationSources = [
              {
                name: "无数据",
                value: 0,
                percent: "0%",
              },
            ]
          }
          // 异常级别分析(换流站)
          this.stationCounts[0].data = res.data.locationLiveOverviews.map((item) => {
            return {
              name: item.locationName,
              value: item.t1,
            };
          });
          this.stationCounts[1].data = res.data.locationLiveOverviews.map((item) => {
            return {
              name: item.locationName,
              value: item.t0,
            };
          });
          this.yName = res.data.locationLiveOverviews.map((item) => item.locationName);
          // 子模块告警设备统计
          this.modelPointCounts.data = siteList.map((item, index) => {
            let arr = [];
            res.data.moduleOverviews.forEach(element => {
              arr.push(
                element.counts.some(key => key.locationName === item.site) ? element.counts.find(key => key.locationName === item.site).count : 0
              )
            });

            return {
              name: item.site,
              barWidth: 10,
              color: index === 0 ?  ["rgba(84, 61, 7, 1)", "rgba(254, 188, 34, 1)"] :index === 1 ? ["#89f480", "#108707"] : ["#83d3f6", "#1ea9ed"],
              data: arr
            }
          })
          this.modelPointCounts.xAxis = res.data.moduleOverviews.map(item => item.dwName)

          // 异常级别分析(子模块告警设备统计)
          this.deviceCounts.xAxis = res.data.liveOverviews.map(
            (item) => item.xname
          );
          this.deviceCounts.data[0].data = res.data.liveOverviews.map(
            (item) => item.t1
          );
          this.deviceCounts.data[1].data = res.data.liveOverviews.map(
            (item) => item.t0
          );

        }
        this.fullscreenLoading = false;
      });
    },
    // 查询
    handleSearch() {
      sessionStorage.setItem(
        "duibifenxiTime",
        JSON.stringify({
          startTime: this.$moment(this.form.startTime).format("YYYY-MM-DD HH:mm:ss"),
          endTime: this.$moment(this.form.endTime).format("YYYY-MM-DD HH:mm:ss"),
        })
      );
      this.init();
    },
    // 重置
    reset() {
      this.form = {
        startTime: this.$moment().subtract(29, "days").startOf("day").valueOf(),
        endTime: this.$moment().endOf("day").valueOf(),
      };
      this.init();
    },
    // 进入实时数据计算 -- 打开弹窗
    handleRealTime() {
      // this.$router.push({ path: "/early" });
      this.huanliuShow = true;
    },

    clickFn(param) {
      let str = '测点';
      if (param.name === '桥臂' || param.name === '内水冷' || param.name === '子模块') {
        str = param.name;
      }
      this.$router.push({
        path: "/alarmHistory",
        query: {
          paramName: str,
        },
      });
    },
    // // 换流站列表
    // async getXjSiteList() {
    //   let result = await getXjSiteList();
    //   if (result.code == 20000) {
    //     this.siteListNew = result.data;
    //   }
    // },
    exportData() {
      this.dialog.visible = true;
      // this.getXjSiteList();
      this.siteListNew = siteList;
      this.dialog.form.date = [
        this.$moment(this.form.startTime).format("YYYY-MM-DD"),
        this.$moment(this.form.endTime).format("YYYY-MM-DD"),
      ];
      this.getXJReportFilePageListData();
    },
    getXJReportFilePageListData() {
      let params = {
        currentPage: this.pager.currentPage,
        endTime: this.$moment(this.dialog.form.date[1]).format("YYYY-MM-DD"),
        size: this.pager.pageSize,
        startTime: this.$moment(this.dialog.form.date[0]).format("YYYY-MM-DD"),
        locationName: this.dialog.form.site
      };
      getXJReportFilePageList(params).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.records;
          this.pager.total = Number(res.data.total);
        }
      });
    },
    // 监听弹窗关闭
    switchVisable(visable, ref) {
      this[ref] = visable;
    },
    // 关闭弹窗
    dialogCancel() {
      this.dialog.visible = false;
    },
    handleSearchDialog() {
      this.getXJReportFilePageListData();
    },
    /**
     * 根据Blob下载文件（Blob即后端的Stream文件类型格式）
     * @params fileName文件名,比如‘2021届学生.xlsx’
     * @params fileBlob文件
     */
    downFileBlob(fileBlob, fileName) {
      const blob = new Blob([fileBlob]);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.style.display = "none";
      a.click();
      document.body.removeChild(a);
    },
    exportExcel() {
      let params = {
        endTime: this.$moment(this.dialog.form.date[1]).unix(),
        site: this.dialog.form.site,
        startTime: this.$moment(this.dialog.form.date[0]).unix(),
      };

      let locUrl =
        process.env.NODE_ENV === "production"
          ? window.productiontIp
          : window.developmentIp;

      Axios.post(locUrl + "/earlyWarn/reportExport", params, {
        responseType: "blob",
      }).then((res) => {
        this.downFileBlob(
          res.data,
          this.$moment().format("YYYY-MM-DD") + "主动预警运行报告.zip"
        );
      });
    },
    handleSizeChange(val) {
      this.pager.pageSize = val;
      this.getXJReportFilePageListData();
    },
    handleCurrentChange(val) {
      this.pager.currentPage = val;
      this.getXJReportFilePageListData();
    },
    downloadFile(url) {
      // 创建一个隐藏的a标签
      var a = document.createElement("a");
      a.href = url;

      // 设置download属性，这样浏览器就知道这是一个下载操作
      a.download = url.substring(url.lastIndexOf("/") + 1);

      // 触发a标签的点击事件
      document.body.appendChild(a);
      a.click();

      // 移除a标签
      document.body.removeChild(a);
    },
    handleButton(method, row, index) {
      let locUrl =
        process.env.NODE_ENV === "production"
          ? window.productiontIp
          : window.developmentIp;
      let url = locUrl + '/zdyj/generateReport/down?id=' + method[1].id;
      handleExportFile(
        url,
        "zip",
        {

        },
        () => {
          console.log('下载成功')
        }
      );
    },
  },
};
</script>

<style lang="less">
.radio-box.form-search.cur-page {
  .el-radio-group {
    padding: 0 10px !important;
  }

  .el-radio {
    &:not(:last-child) {
      margin-right: 10px;
    }
  }
}
</style>

<style scoped lang="less">
.statistic {
  height: 100%;
  width: 100%;
  box-sizing: border-box;

  .top {
    display: flex;
    justify-content: space-between;
  }

  .echarts-wrapper {
    height: calc(100% - 50px);
    margin-top: 10px;
    display: flex;
    justify-content: space-between;

    .echarts-wrapper-item {
      width: calc(100% - 10px);
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      ::v-deep .sec-wrapper {
        height: calc(50% - 10px);

        &:last-child {
          margin-top: 20px;
        }
      }

      &:first-child {
        margin-right: 20px;
      }
    }
  }
}

.caidan_yangshi {
  display: flex;
  align-items: center;
}
</style>
